package com.wuyu.acl.controller;

import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNodeConfig;
import cn.hutool.core.lang.tree.TreeUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wuyu.acl.common.Result;
import com.wuyu.acl.po.DictData;
import com.wuyu.acl.po.DictType;
import com.wuyu.acl.po.Permission;
import com.wuyu.acl.po.RolePermission;
import com.wuyu.acl.service.DictDataService;
import com.wuyu.acl.service.DictTypeService;
import com.wuyu.acl.service.PermissionService;
import com.wuyu.acl.service.RolePermissionService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Tag(name = "权限管理")
@RestController
@RequestMapping("/admin/acl/permission")
public class PermissionController {

    @Resource
    private PermissionService permissionService;

    @Resource
    private RolePermissionService rolePermissionService;

    @Resource
    private DictTypeService dictTypeService;

    @Resource
    private DictDataService dictDataService;

    /**
     * 权限管理：查询所有权限（树状）
     *
     * @return
     */
    @Operation(summary = "查询所有权限（树状）")
    @GetMapping
    public Result permissionTree() {
        List<Permission> permissionList = permissionService.list();
        TreeNodeConfig config = new TreeNodeConfig();
        config.setIdKey("id");
        config.setParentIdKey("pid");
        config.setNameKey("name");
        config.setWeightKey("sortProp");
        config.setChildrenKey("children");
        List<Tree<Long>> treeList = TreeUtil.build(permissionList, 0L, config, (permission, treeNode) -> {
            treeNode.setId(permission.getId());
            treeNode.setParentId(permission.getPid());
            treeNode.setName(permission.getName());
            treeNode.setWeight(permission.getSortProp());
            treeNode.putExtra("code", permission.getCode());
            treeNode.putExtra("type", permission.getType());
        });
        return Result.ok(treeList);
    }

    /**
     * 权限管理：查询所有的非按钮权限列表（父级目录）
     *
     * @return
     */
    @Operation(summary = "查询所有的非按钮权限列表（父级目录）")
    @GetMapping("/parent")
    public Result getParentPermission() {
        List<Permission> parentPermission = permissionService.list(new LambdaQueryWrapper<Permission>()
                .eq(Permission::getType, 1));
        return Result.ok(parentPermission);
    }

    /**
     * 权限管理：查询权限的类型（路由|按钮）
     *
     * @param code
     * @return
     */
    @Operation(summary = "查询权限的类型（路由|按钮）")
    @GetMapping("/dict/{dictTypeCode}")
    public Result permissionType(@PathVariable("dictTypeCode") String code) {
        DictType dictType = dictTypeService.getOne(new LambdaQueryWrapper<DictType>()
                .eq(DictType::getCode, code));
        List<DictData> dictDataList = dictDataService.list(new LambdaQueryWrapper<DictData>()
                .eq(DictData::getTypeId, dictType.getId())
                .orderByAsc(DictData::getSortProp));
        return Result.ok(dictDataList);
    }

    /**
     * 权限管理：添加权限
     *
     * @param permission
     * @return
     */
    @Operation(summary = "添加权限")
    @PostMapping
    public Result add(@RequestBody Permission permission) {
        Long pid = permission.getPid();
        // 1. 在角色权限表中，删除pid对应的所有记录（全开变半开）
        rolePermissionService.remove(new LambdaQueryWrapper<RolePermission>()
                .eq(RolePermission::getPermissionId, pid));
        // 2. 添加权限
        permissionService.save(permission);
        return Result.ok();
    }

    /**
     * 权限管理：修改权限
     *
     * @param permission
     * @return
     */
    @Operation(summary = "修改权限")
    @PutMapping
    public Result update(@RequestBody Permission permission) {
        permissionService.updateById(permission);
        return Result.ok();
    }

    /**
     * 权限管理：删除权限
     *
     * @param id
     * @return
     */
    @Operation(summary = "删除权限")
    @DeleteMapping("/{id}")
    public Result remove(@PathVariable("id") Long id) {
        permissionService.removeRecursion(id);
        return Result.ok();
    }

}
